package com.xiamo.job;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xiamo.entity.BillRecord;
import com.xiamo.entity.WxPushLog;
import com.xiamo.entity.WxUser;
import com.xiamo.security.SecurityService;
import com.xiamo.service.IWxPushLogService;
import com.xiamo.service.IWxUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import java.sql.Wrapper;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class PushJob {

    @Autowired
    private SecurityService securityService;

    @Autowired
    private IWxUserService wxUserService;

    @Autowired
    private IWxPushLogService wxPushLogService;

    @Scheduled(cron = "0 0 20 * * *") // 每天晚上20点执行
    public void scheduledTask() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat sdfs = new SimpleDateFormat("yyyy年MM月dd日");

        Date currentTime = new Date();
        String formattedTime = sdf.format(currentTime);
        String formattedTimes = sdfs.format(currentTime);
        RestTemplate restTemplate = new RestTemplate();

        List<WxUser> wxUserList = wxUserService.list(Wrappers.<WxUser>lambdaQuery()
                .eq(WxUser::getIsPush, 1));

        // 调用 securityService 中的方法
        String accessToken = securityService.getToken();
        for (WxUser wxUser : wxUserList) {
            String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;

            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/json");

            String jsonBody = "{\n" +
                    "    \"touser\": \"" +wxUser.getOpenId()+ "\",\n" +
                    "    \"template_id\": \"2BkLqy8kw0mkGjmBh_73RDXLve4P16gpwnl3hVfSuDY\",\n" +
                    "    \"page\": \"pages/index/index\",\n" +
                    "    \"miniprogram_state\": \"formal\",\n" +//正式版本
                    "    \"lang\": \"zh_CN\",\n" +
                    "    \"data\": {\n" +
                    "        \"time1\": {\n" +
                    "            \"value\": \"" + formattedTimes + "\"\n" +
                    "        },\n" +
                    "        \"thing3\": {\n" +
                    "            \"value\": \"" + "亲爱的" + wxUser.getNickname() + "记得来记账哦~" + "\"\n" +
                    "        }\n" +
                    "    }\n" +
                    "}";

            HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);

            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

            WxPushLog wxPushLog = new WxPushLog();
            wxPushLog.setTemplateId("2BkLqy8kw0mkGjmBh_73RDXLve4P16gpwnl3hVfSuDY");
            wxPushLog.setCreateTime(new Date());
            wxPushLog.setTouser(wxUser.getOpenId());

            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                wxPushLog.setStatus("push success");
                log.info("订阅消息发送成功");
            } else {
                wxPushLog.setStatus("push fail");
                log.error("订阅消息发送失败");
            }
            wxPushLogService.save(wxPushLog);
        }
    }

}
